package cn.iocoder.yudao.module.book.service.author;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.book.controller.admin.author.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.author.AuthorDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.book.dal.mysql.author.AuthorMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

/**
 * 作者 Service 实现类
 *
 *
 */
@Service
@Validated
public class AuthorServiceImpl implements AuthorService {

    @Resource
    private AuthorMapper authorMapper;

    @Override
    public Long createAuthor(AuthorSaveReqVO createReqVO) {
        // 插入
        AuthorDO author = BeanUtils.toBean(createReqVO, AuthorDO.class);
        authorMapper.insert(author);
        // 返回
        return author.getId();
    }

    @Override
    public void updateAuthor(AuthorSaveReqVO updateReqVO) {
        // 校验存在
        validateAuthorExists(updateReqVO.getId());
        // 更新
        AuthorDO updateObj = BeanUtils.toBean(updateReqVO, AuthorDO.class);
        authorMapper.updateById(updateObj);
    }

    @Override
    public void deleteAuthor(Long id) {
        // 校验存在
        validateAuthorExists(id);
        // 删除
        authorMapper.deleteById(id);
    }

    private void validateAuthorExists(Long id) {
        if (authorMapper.selectById(id) == null) {
            throw exception(AUTHOR_NOT_EXISTS);
        }
    }

    @Override
    public AuthorDO getAuthor(Long id) {
        return authorMapper.selectById(id);
    }

    @Override
    public PageResult<AuthorDO> getAuthorPage(AuthorPageReqVO pageReqVO) {
        return authorMapper.selectPage(pageReqVO);
    }

}